package com.gusti.vlc.services.impl;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.gusti.vlc.services.IVlcService;
import com.gusti.vlc.util.Debug;
import com.gusti.vlc.util.VlcResponse;

/**
 * 
 * @author gusti
 *
 */
@Service
public class VlcService implements IVlcService {

	private static final String SERVER_PROTOCOL = "http";
	private static final String SERVER_URL = "localhost";
	private static final int SERVER_PORT = 8080;

	public VlcResponse executeStatusCommand( String command ) {
		VlcResponse vlcResponse = new VlcResponse();

		DefaultHttpClient httpClient = new DefaultHttpClient();
		try {

			HttpResponse response = execute( httpClient, buildHttpHost(), buildRequesStatusHttpGetCommand( command ) );

			if( response != null ) {
				vlcResponse.setStatusCode( response.getStatusLine().getStatusCode() );

				HttpEntity entity = response.getEntity();
				if( entity != null ) {
					Gson gson = new Gson();
					Object fromJson = gson.fromJson( EntityUtils.toString( entity ), Object.class );
					vlcResponse.setData( fromJson );
				}
			}

		} catch (ClientProtocolException e) {
			Debug.error( e );
		} catch (IOException e) {
			Debug.error( e );
		} finally {
			// When HttpClient instance is no longer needed,
			// shut down the connection manager to ensure
			// immediate deallocation of all system resources
			httpClient.getConnectionManager().shutdown();
		}

		return vlcResponse;
	}

	/**
	 * 
	 * @return HttpHost
	 */
	private HttpHost buildHttpHost() {
		return new HttpHost( SERVER_URL, SERVER_PORT, SERVER_PROTOCOL );
	}

	/**
	 * 
	 * @param command
	 * @return HttpGet
	 */
	private HttpGet buildRequesStatusHttpGetCommand( String command ) {
		if( command != null ) {
			return new HttpGet( "/requests/status.json?command=" + command );
		}
		return new HttpGet( "/requests/status.json" );
	}

	/**
	 * 
	 * @param httpclient
	 * @param target
	 * @param request
	 * @return HttpResponse
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	private HttpResponse execute( DefaultHttpClient httpclient, HttpHost target, HttpGet request ) throws ClientProtocolException, IOException {
		Debug.log("executing request to " + target);
		Debug.log("executing request " + request.getURI());

		return httpclient.execute( target, request );
	}
}
